var _id='',_ids = [],_specArr = [];
var login = false;
var total = 100;
var min = 1;
$(function(){

    post({
        url : "/isLogin",
        success : function(data){
            if(!data){
                login = false;
                emptyCart();
            }else{
                login = true;
                getCartListData();
            }
        }
    });

    reset();
    deleteProduct();//删除商品
    changeNum();//购买数量
});

//点击去结算
$(".account .btn ").click(function(){

    if(_ids.length>0){
        setCookie("mobile_cartId",_ids.toString());
        post({
            url:"/order/queryOrderCode",
            data:{id:_ids.toString()},
            success:function(data){
                setCookie("orderCode",data);
                go("/mobileorder/index.html");
            }
        });
    }
});

//点击编辑，弹出选择商品规格
$(".handle").delegate(".p_editor","click",function(){
    $(".c_container").css("display","block");
    $(".cover").animate({"opacity":"0.5"},"500");
    $(".c_main").animate({"bottom":"0%"},"500");
});

//点击确定按钮
$(".c_main .btn").click(function(){

    if(isEmpty(_specArr)){
        if(login){
            if(total>0){
                post({
                    url:"/cart/edit",
                    data:{ids:_id,specGroup:_specArr.toString(),num:$(".num .middle input").val()},
                    success:function(data){
                        _specArr = [];
                        $(".c_main").animate({"bottom":"-120%"},"500");
                        $(".cover").animate({"opacity":"0"},"500");
                        setTimeout(function(){
                            $(".c_container").css("display","none");
                        },500);
                        $(".icon_cart").removeClass("back-select");
                        var chkAll=document.querySelector(".selectAll");
                        chkAll.checked=false;
                        getCartListData();
                    }
                })
            }
        }else{
            $(".login_alert").css("display","block");
            setTimeout(function(){
                $(".login_alert").css("display","none");
            },3000)
        }
    }else{
        $(".select_alert").css("display","block");
        setTimeout(function(){
            $(".select_alert").css("display","none");
        },3000)
    }
});

//点击关闭 选择商品规格弹窗
$(".c_main .close").click(function(){

    _specArr = [];
    $(".c_main").animate({"bottom":"-120%"},"500");
    $(".cover").animate({"opacity":"0"},"500");
    setTimeout(function(){
        $(".c_container").css("display","none");
    },500)
});

//获取购物车列表数据
function getCartListData(){
    post({
        url: "/cart/list",
        success: function (data) {
            console.log(data);
            dealCartGoods(data);
        }
    });
}

//处理购物车列表数据
function dealCartGoods(data){
     var _html = '';
     for(var i=0;i<data.length;i++){
         _html += '<div class="list">';
         _html += '<div class="list_detail">';
         if(data[i].enabled){
             _html += '<div style="background-image: url(img/round.png);" class="range left"><input type="checkbox" class="single_chk" data-price="'+(data[i]["amount"])+'" data-num="'+data[i]["num"]+'" data-id="'+data[i]["id"]+'"/></div>'
        }else{
            _html += '<div class="range left"><span>失效</span></div>'
        }

         _html += '<div class="img left"><img src="'+SERVER_CONTEXT_PATH+'/load/picture/'+data[i]["imageUrl"]+'"></div>';
         _html += '<div class="info left">';
         _html += '<p class="more_single"><a href="../productdetail/index.html#'+data[i]["productId"]+'">'+data[i]["productName"]+'</a></p>';
         _html += '<p class="price more_single">￥<a>'+(data[i]["price"]).toFixed(2)+'</a><span class="right">X&nbsp;';
         _html += data[i]["num"]+'</span></p><p class="more_single">';
         for(var j=0;j<data[i]["specifications"].length;j++){
             _html += data[i]["specifications"][j]["specValue"]+"&nbsp;";
         }
         _html += '</p></div></div>';
         _html += '<div class="handle">';
         _html += '<span class="right p_delete" data-id="'+data[i]["id"]+'">删除</span>';
         _html += '<span class="right p_editor" data-productid="'+data[i]["productId"]+'" data-id="'+data[i]["id"]+'" data-num="'+data[i]["num"]+'">编辑</span></div>';
         _html += '</div>';
     }

     if(data.length ==0){
         emptyCart();
     }else{
         $(".main").html(_html);
     }

     selcetProduct();//勾选商品
     $(".p_editor").click(function(){
         var productId = $(this).data("productid");
         _id = $(this).data("id");
         $(".num .middle input").val($(this).data("num"));
         editProduct(productId);
     })
 }

//勾选购物车商品
 function selcetProduct(){

     var chk=document.querySelectorAll(".single_chk");  //单选按钮
     var chkAll=document.querySelector(".selectAll");
     var flag=true;
     $(".single_chk").click(function(){//单选
         flag=true;
         for(var k=0;k<chk.length;k++){
             if(chk[k].checked==false){
                 flag=false;
             }
         }
         countPrice();
     });

     $(".selectAll").click(function(){  //全选
         $(".single_chk").prop("checked",chkAll.checked);
         countPrice();
     });
 }

//计算总价格
function countPrice(){

     var flag = true;
     var _price=0;
     var num = 0;
     var chkAll=document.querySelector(".selectAll");
     _ids =[];
     $(".single_chk").each(function(index){
         if($(this).prop("checked")){
             _price += $(this).data("price");
             num += $(this).data("num");
             _ids.push($(this).data("id"));
             $(this).parent().addClass("back-select");
         }else{
             $(this).parent().removeClass("back-select");
             flag = false;
         }
     });
     chkAll.checked=flag;
     if(flag == true){
         $(".icon_cart").addClass("back-select");
     }else{
         $(".icon_cart").removeClass("back-select");
     }
     $(".total_price").text("￥"+_price.toFixed(2));
     $(".account .btn span").text("("+num+")");
 }

//选择规格
function specification(productId,data){
    //规格
    var _spec = '';
    for(var k=0;k<data["specifications"].length;k++){
        _spec += '<li><p>'+data["specifications"][k]["name"]+'</p>';
        for(var n=0;n<data["specifications"][k]["specValues"].length;n++){
            _spec += '<span data-id="'+data["specifications"][k]["specValues"][n]["id"]+'">';
            _spec += ''+data["specifications"][k]["specValues"][n]["specValue"]+'</span>';
        }
        _spec += '</li>';
        _specArr.push('');
    }

    $(".specification ul").html(_spec);
    $(".c_detail .img img").attr("src",SERVER_CONTEXT_PATH+"/load/picture/"+data.imageUrl);
    $(".c_detail .price").html('价格：<span>￥'+(data.retailPrice).toFixed(2)+'</span>');

    var _arr = [];
    $(".specification li").each(function(i){
        _arr[i] = "";
        $(this).find("span").click(function(){
            if(!!$(this).hasClass("red_back")){
                $(this).removeClass("red_back");
                _arr[i] = "";
                _specArr[i] = '';
            }else{
                _arr[i] = $(this).text();
                $(this).addClass("red_back").siblings("span").removeClass("red_back");
                _specArr[i] = $(this).data("id");
            }
            showSpec(_arr);
            getPrice(productId,_specArr);
        });
    });
}

//显示已选择的规格
function showSpec(arr){
    arr = removeItem(arr);
    var str = "请选择规格";
    if(arr.length != 0){
        str = '已选择';
        for(var i=0;i<arr.length;i++){
            str += " " + arr[i];
        }
    }
    $(".c_main .spec").text(str);
}

//读取价格与库存
function getPrice(productId,arr){
    var flag = true;
    for(var i=0;i<arr.length;i++){
        if(arr[i]==''){
            flag = false;
        }
    }
    if(flag){
        post({
            url:"/product/getProductSkuInfo",
            data:{productId:productId,specGroup:arr.toString()},
            success:function(data){
                total = data.merchantTotal;
                $(".c_detail .price").html('价格：<span>￥'+(data.price).toFixed(2)+'</span>');
                $(".c_detail .total").html('库存'+data.total+'件');
                $(".num input").val(min);
                $(".num span").text("(可购买 "+total+" 件)");
                $(".visual").css("visibility","visible");
                if(total>0){
                    $(".c_main .btn").css({"opacity":"1","background-color":"#ea540a"});
                }else{
                    $(".c_main .btn").css({"opacity":"0.65","background-color":"#cccccc"});
                }
            }
        })
    }else{
        $(".visual").css("visibility","hidden");
        $(".c_main .btn").css({"opacity":"0.65","background-color":"#cccccc"});
    }
}

//购买数量
function changeNum(){
    //数量加1
    $(".num .add").click(function(){
        var num = parseInt($(".num .middle input").val());
        $(".num .add").css("opacity","1");
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            if(num>=total){
                $(".num .middle input").val(total);
                $(".num .add").css("opacity","0.3");
            }else{
                $(".num .middle input").val(num+1);
            }
        }
    });

    //数量减1
    $(".num .minus").click(function(){
        var num = parseInt($(".num input").val());
        $(".num .minus").css("opacity","0.3");
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            if(num>min){
                $(".num input").val(num-1);
                if(num-min > 1){
                    $(".num .minus").css("opacity","1");
                }
            }else{
                $(".num input").val(min);
            }
        }
    });

    //输入数量
    $(".num input").blur(function(){
        if(total<=0){
            $(".num .middle input").val(0);
        }else{
            var _val = $(this).val();
            if(isNaN(_val)||_val<=min){
                $(this).val(min);
                $(".num .minus").css("opacity","0.3");
            }else{
                $(".num .minus").css("opacity","1");
                var num = parseInt($(this).val());
                if(num>=total){
                    $(this).val(total);
                    $(".num .add").css("opacity","0.3");
                }else{
                    $(this).val(Math.ceil(_val));
                    $(".num .add").css("opacity","1");
                }
            }
        }
    });
}

//编辑商品
function editProduct(productId){

    $(".c_container").css("display","block");
    $(".cover").animate({"opacity":"0.5"},"500");
    $(".c_main").animate({"bottom":"0%"},"500");
    post({
        url:'/product/'+productId+'/detail',
        success:function(data){
            //console.log(data)
            specification(productId,data);
        }
    })
}

//删除商品
function deleteProduct(){

    var cartId = '';
    var _this = '';
    $(".main").delegate(".p_delete","click",function(){
        cartId = $(this).data("id");
        _this = $(this);
        $('.gat_background').removeClass('tab');
        $('.gat_alert').addClass('animated slideInDown');

    });

    $('.gat_alert_affirm').click(function () {
        post({
            url:"/cart/delete",
            data:{ids:cartId},
            success:function(data){
                _this.parent().parent().remove();
                var _inner = $(".main").html();
                if(_inner == ""){
                    emptyCart();
                }
                $('.gat_background').addClass('tab');
            }
        });
    });

    $('.gat_alert_cancel').click(function () {
        $('.gat_background').addClass('tab');
    });
}

//购物车为空时显示的内容
function emptyCart(){
    var _h = '<div class="empty"><img src="../common/img/gouwuche.png">';
    _h += '<p>&nbsp;&nbsp;购物车是空的～</p></div>';
    $(".main").html(_h);
}

//下边 结算距离
function reset(){
    var _h = $("#bottom").height();
    $(".account").css("bottom",_h+1+"px");
    $(".main").css("padding-bottom",_h+$(".account").height()+1+"px");
}

//移除数组的空元素
function removeItem(arr){
    var newArr=[];
    for(var i=0;i<arr.length;i++){
        if(arr[i] != ""){
            newArr.push(arr[i]);
        }
    }
    return newArr;
}

//判断数组是否有空元素
function isEmpty(arr){
    var flag = true;
    for(var i=0;i<arr.length;i++){
        if(arr[i] == ""){
            flag = false;
        }
    }
    return flag;
}

//判断是否是微信
function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }else{
        return false;
    }
}